<template>
  <div class="orders-container">
    <el-card class="orders-management-card">
      <h3>订单管理</h3>
      <el-row>
        <!-- 查询表单-->

      </el-row>
      <el-table border :data="orderState.orderItems" style="width: 100%">
        <el-table-column prop="orderId" label="订单号" width="150"/>
        <el-table-column label="用户" width="180">
          <template #default="scope">
            {{ scope.row.sysUser.userName }}
          </template>
        </el-table-column>
        <el-table-column label="地址" width="180">
          <template #default="scope">
            {{ scope.row.address.address }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column label="结算方式">
          <template #default="scope">
            <span>{{ scope.row.giveType === 0 ? '积分' : '现金' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalMoney" label="金额"/>
        <el-table-column prop="totalPoint" label="积分"/>
        <el-table-column label="状态">
          <template #default="scope">
            <span v-if="scope.row.status === 0">进行中</span>
            <span v-else-if="scope.row.status === 1">完成</span>
            <span v-else-if="scope.row.status === 2">取消</span>
            <span v-else-if="scope.row.status === 3">异常</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300px" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleOrderDetail(scope.row)">详情</el-button>
            <!--            <el-button type="text" @click="handleDeleteOrder(scope.row)">删除</el-button>-->
            <el-button type="text" v-if="scope.row.status === 0" @click="finishOrder(scope.row)">完成</el-button>
            <el-button v-if="scope.row.status === 0" type="text" @click="handleCancelOrder(scope.row)">取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="orderState.currentPage"
          :page-size="orderState.pageSize"
          :total="orderState.total"
          layout="prev, pager, next"
          @current-change="handleOrderPageChange"
      />
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="orderDetailDialogVisible" title="订单详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">{{ orderDetail.orderId }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{ orderDetail.sysUser.userName }}</el-descriptions-item>
        <el-descriptions-item label="地址">{{ orderDetail.address.address }}</el-descriptions-item>
        <el-descriptions-item label="结算方式">{{ orderDetail.giveType === 0 ? '积分' : '现金' }}</el-descriptions-item>
        <el-descriptions-item label="金额">{{ orderDetail.totalMoney }}</el-descriptions-item>
        <el-descriptions-item label="积分">{{ orderDetail.totalPoint }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <span v-if="orderDetail.status === 0">进行中</span>
          <span v-else-if="orderDetail.status === 1">完成</span>
          <span v-else-if="orderDetail.status === 2">取消</span>
          <span v-else-if="orderDetail.status === 3">异常</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-row title="订单详情" border>

        <el-table border :data="orderDetails" style="width: 100%">
          <el-table-column prop="medicineCount" label="药品数量"/>
          <el-table-column prop="medicines.medicineName" label="药品名"/>
        </el-table>
      </el-row>
      <template #footer>
        <el-button type="primary" @click="orderDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, onMounted, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {getOrderList, updateOrder, deleteOrder, getOrderDetail, overOrder, cancelOrder} from '@/api/order';

const orderState = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0,
  pages: 1,
  orderItems: []
});

const orderDetail = ref({});
const orderDetailDialogVisible = ref(false);

onMounted(() => {
  fetchOrders();
});

const fetchOrders = () => {
  getOrderList({
    current: orderState.currentPage,
    size: orderState.pageSize
  }).then(response => {
    orderState.orderItems = response.data.data.records;
    orderState.total = response.data.data.total;
    orderState.currentPage = response.data.data.current;
    orderState.pages = response.data.data.pages;
  }).catch(error => {
    console.error('获取订单数据失败:', error);
    ElMessage.error('获取订单数据失败');
  });
};

const handleOrderPageChange = (page) => {
  orderState.currentPage = page;
  fetchOrders();
};

const orderDetails = ref([]);

const handleOrderDetail = async (order) => {
  Object.assign(orderDetail.value, order)
  await getOrderDetail(order.orderId).then((res) => {
    // orderDetail.value = res.data.data;
    Object.assign(orderDetail.value, res.data.data)
    orderDetails.value = res.data.data.orderDetailDtos
    console.log("最终的详情：", orderDetail.value)
    console.log("最终的详情：", orderDetails.value)
    orderDetailDialogVisible.value = true;
  }).catch(error => {
    console.log('获取订单详情失败', error);
  });
};

const handleDeleteOrder = (order) => {
  ElMessageBox.confirm('确定删除该订单吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrder(order.orderId).then(response => {
      ElMessage.success('删除订单成功');
      orderState.orderItems = orderState.orderItems.filter(item => item.orderId !== order.orderId);
    }).catch(error => {
      console.error('删除订单失败:', error);
      ElMessage.error('删除订单失败');
    });
  }).catch(() => {
    // 用户取消删除
  });
};

const handleCancelOrder = (order) => {
  ElMessageBox.confirm('确定取消该订单吗？', '取消确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 取消订单
    cancelOrder(order.orderId).then(response => {
      ElMessage.success('取消订单成功');
      order.status = 2; // 更新订单状态为取消
    }).catch(error => {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单失败');
    });
  }).catch(() => {
    // 用户取消操作
  });
};
const finishOrder = (order) => {
  ElMessageBox.confirm('确定完成该订单吗？', '完成确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await overOrder(order.orderId).then(response => {
      ElMessage.success('完成订单成功');
      order.status = 1; // 更新订单状态为完成
    }).catch(error => {
      console.error('完成订单失败:', error);
    })
  })
}
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.orders-management-card {
  margin-bottom: 20px;
}
</style>